package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;


    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //菜品要插入，口味要插入
        //DTO数据转换为Entity数据
        Dish dish = new Dish();
        dish.setStatus(StatusConstant.DISABLE);
        BeanUtils.copyProperties(dishDTO, dish);
        //插入到dish中
        dishMapper.insert(dish);//TODO 让主键回显

        //口味
        //因为菜品表和口味表，是一对多关系，口味表是从表插入数据需要菜品的ID
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            //将dishId给到Flavor
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            //访问DishFlavorMapper 插入数据
            dishFlavorMapper.insertBatch(flavors);
        }


    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断菜品有没有起售中的菜品，如果有不能删除
        ids.forEach(id -> {
            //根据id获取菜品
            Dish dish = dishMapper.getById(id);
            //判断状态是否为启用，如果为启用不能删除
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //中断逻辑，抛出异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //判断菜品是否存在于套餐中，如果有不能删
        //找到存在菜品的套餐
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishId(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            //抛出异常中断逻辑
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        //删除菜品，并且删除菜品对应的口味
        ids.forEach(id -> {
            dishMapper.deleteById(id);//菜品删除
            //口味删除
            dishFlavorMapper.deleteByDishId(id);
        });

    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //1 查询菜品数据
        Dish dish = dishMapper.getById(id);
        //2 查询菜品关联的口味
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        //3 将菜品和口味封装到VO中，并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);//将菜品数据拷贝到vo中
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Override
    @Transactional
    public void updateDishWithFlavor(DishDTO dishDTO) {
        //1 修改菜品数据
        Dish entity = new Dish();
        BeanUtils.copyProperties(dishDTO,entity);
        dishMapper.update(entity);

        //2 删除原有菜品的口味
        dishFlavorMapper.deleteByDishId(entity.getId());

        //3 插入新的口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null && flavors.size()>0) {
            //口味数据中需要设置菜品id
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(entity.getId());
            }
            //将口味数据插入到表中
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
